﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net.Sockets;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Modbus.Device;


namespace FactoryIOCSharp_AtoB
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }


        [DllImport("WININET", CharSet = CharSet.Auto)]
        static extern bool InternetGetConnectedState(ref InternetConnectionState IpdwFlags, int dwReserved);
        enum InternetConnectionState : int
        {
            INTERNET_CONNECTION_MODEM = 0x1,
            INTERNET_CONNECTION_LAN = 0x2,
            INTERNET_CONNECTION_PROXY = 0x4,
            INTERNET_RAS_INSTALLED = 0x10,
            INTERNET_CONNECTION_OFFLINE = 0x20,
            INTERNET_CONNECTION_CONFIGURED = 0x40
        }
        TcpClient tcpClient = new TcpClient();
        ModbusIpMaster master;
        string ipAddress;
        int tcpPort;
        ushort deviceID = 1;

        DateTime dtDisconnect = new DateTime();
        DateTime dtNow = new DateTime();
        bool NetworklsOk = false;
        

        private void Form1_Load(object sender, EventArgs e)
        {
            toolStripLabelStateMessage.Text = "初始化成功";
            ipAddress = "192.168.56.1";
            tcpPort = 520;
        }

        private void btnConnect_Click(object sender, EventArgs e)
        {
            // when button clicked, connect to Modbus TCP Server
            TcpClient tcpClient = new TcpClient();
            if (!tcpClient.Connected)
            {
                string ipAddress = textBoxIP.Text;
                int tcpPort = Convert.ToInt32(textBoxPort.Text.Trim());

                NetworklsOk = Connect();
                timer1.Enabled = true;
            }
            else
            {
                tcpClient.Close();
                btnConnect.Text = "连接";
            }
            
           
        }

        private bool Connect()
        {
            if (master != null)
                master.Dispose();
            if (tcpClient != null)
                tcpClient.Close();
            if (CheckInternet())
            {
                try
                {
                    tcpClient = new TcpClient();
                    IAsyncResult asyncResult = tcpClient.BeginConnect(ipAddress, tcpPort, null, null);
                    asyncResult.AsyncWaitHandle.WaitOne(1900, true); //wait for 3 sec
                    if (!asyncResult.IsCompleted)
                    {
                        tcpClient.Close();
                        textBoxMessage.AppendText(DateTime.Now.ToString() + ":无法连接到服务器." + "\r\n");
                        btnConnect.Text = "连接";
                        toolStripLabelStateMessage.Text = "服务器无法连接";
                        return false;
                    }
                    // create Modbus TCP Master by the tcpclient
                    master = ModbusIpMaster.CreateIp(tcpClient);
                    master.Transport.Retries = 0; //don't have to do retries
                    master.Transport.ReadTimeout = 1500;
                    textBoxMessage.AppendText(DateTime.Now.ToString() + ":已连接到服务器" + "\r\n");
                    btnConnect.Text = "断开";
                    toolStripLabelStateMessage.Text = "服务器已连接";
                    return true;
                }
                catch (Exception ex)
                {
                    textBoxMessage.AppendText(DateTime.Now.ToString() + ":连接过程" + ex.StackTrace +
                    "==>" + ex.Message + "\r\n");
                    return false;
                }
            }
            return false;
        }
        private bool CheckInternet()
        {
            

            InternetConnectionState flag = InternetConnectionState.INTERNET_CONNECTION_LAN;
            return InternetGetConnectedState(ref flag, 0);
        }
        private void timer1_Tick(object sender, EventArgs e)
        {
            //start timerl, timerl.Interval = 2000 ms 
            try
            {
                if (NetworklsOk)
                {
                    #region Master to Slave
                    //read Al. AO, DL DO 
                    bool[] readinput = master.ReadInputs(deviceID,10);
                    for (int i = 0; i < 10; i++)
                    {
                        textBoxMessage.AppendText("readinput[i]");
                    }
                    #endregion
                }
                else
                {
                    //retry connecting
                    dtNow = DateTime.Now;
                    if ((dtNow - dtDisconnect) > TimeSpan.FromSeconds(20))
                    {
                        textBoxMessage.AppendText(DateTime.Now.ToString() + "开始连接..." + "\r\n");
                        NetworklsOk = Connect();
                        if (!NetworklsOk)
                        {
                            textBoxMessage.AppendText(DateTime.Now.ToString() + ":连接失败，等待重连" + "\r\n");
                            dtDisconnect = DateTime.Now;
                        }
                    }
                    else
                    {
                        textBoxMessage.AppendText(DateTime.Now.ToString() + ":等待重新连接" + "\r\n");
                    }
                }
            }
            catch (Exception ex)
            {
                if (ex.Source.Equals("System"))
                {
                    //set NetworkIsOK to false and retry connecting
                    NetworklsOk = false;
                    textBoxMessage.AppendText(ex.Message + "\r\n");
                    dtDisconnect = DateTime.Now;

                }
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            textBoxMessage.AppendText("按钮1已按下  "+ DateTime.Now.ToString() + "\r\n");
        }

        private void button2_Click(object sender, EventArgs e)
        {
            textBoxMessage.AppendText("按钮2已按下  "+ DateTime.Now.ToString() + "\r\n");
        }

        private void Form1_FormClosed(object sender, FormClosedEventArgs e)
        {
            if (tcpClient.Connected)
            {
                tcpClient.Close();
            }
        }
    }
}









//            string ipAddress = textBoxIP.Text;
//            int tcpPort = Convert.ToInt32(textBoxPort.Text.Trim());
//            try
//            {
//                TcpClient tcpClient = new TcpClient();
//                tcpClient.BeginConnect(ipAddress, tcpPort, null, null);
//                ModbusIpMaster master = ModbusIpMaster.CreateIp(tcpClient);
//                if (tcpClient.Connected)
//                {
//                    lblConnectState.Text = "连接上了";
//                    lblConnectState.ForeColor = Color.Green;
//                }
//                byte slaveID = 1;
//                ushort startAddress = 0;
//                ushort numOfPoints = 10;
//                bool[] coilstatus = master.ReadInputs(slaveID, startAddress, numOfPoints);

//                for (int r = 0; r < 20; r++)
//                {
//                    arr[r] = coilstatus[r];
//                }

//            }
//            catch (Exception)
//            {

//                MessageBox.Show("没服务器吧！");
//            }


//            if (arr[0] == true)
//            {
//                textBoxMessage.Text = "服务器" + "上线" + Environment.NewLine;
//            }



//            byte[] buffer = new byte[1024 * 1024 * 1];

//            if (arr[0] == false)
//            {
//                textBoxMessage.AppendText("服务器" + "下线" + Environment.NewLine);
//            }


//        }


//    }
//}
